const express = require('express')
const cors = require('cors')
const expressJwt = require('express-jwt')
const login = require('./routers/login')
const user = require('./routers/user')
const cates = require('./routers/cates')

const app = express()

// 处理跨域
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(
  expressJwt({ secret: 'big-event', algorithms: ['HS256'] }).unless({
    path: [/^\/api/],
  })
)

app.listen('3000', () => {
  console.log('大事件服务器开启') 
})

app.use('/api', login)
app.use('/my', user)
app.use('/my/article', cates)

// 错误中间件，统一处理后端的错误
app.use((err, req, res, next) => {
  // token解析失败导致的错误
  if (err.name === 'UnauthorizedError') {
    return res.send({
      status: 401,
      message: '无效的token',
    })
  }
  // 其他原因导致的错误
  res.send({
    status: 500,
    message: '服务器异常',
  })
})
